package com.hy.utils;

import com.google.gson.Gson;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import org.apache.http.NameValuePair;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ssl.DefaultHostnameVerifier;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.TrustSelfSignedStrategy;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.ssl.SSLContextBuilder;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.net.ssl.SSLContext;
import java.security.KeyManagementException;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Component
public class RobotUtils {
    //日志
    private static final Logger log = LoggerFactory.getLogger(RobotUtils.class);
    //存储APIkey
    public static final String API_KEY = "5b30ab5eb66e476bb069d471341e16eb";
    //存储接口请求地址
    public static final String url = "http://openapi.tuling123.com/openapi/api/v2";
    // 用户id
    public static final String USER_ID = "311630";



    /**
     * 获取可以传输的正确的json格式的请求字符串
     * @param reqMes 输入内容
     * @return
     */
    public Map<String,Object> getReqMes(String reqMes){
        // 请求json，里面包含reqType，perception，userInfo
        HashMap<String, Object> reqJson = new HashMap<>();
        HashMap<String, Object> perception = new HashMap<>();
        HashMap<String, Object> inputText = new HashMap<>();
        HashMap<String, Object> userInfo = new HashMap<>();

        // 输入类型:0-文本(默认)、1-图片、2-音频
        int reqType = 0;
        reqJson.put("reqType",reqType);

        // 输入信息,里面包含inputText，inputImage，selfInfo
        inputText.put("text",reqMes);
        // 输入的文本信息
        perception.put("inputText",inputText);
//        // 输入的图片信息
//        JSONObject inputImage = new JSONObject();
//        inputImage.put("url","");
//        perception.put("inputImage",inputImage);
//        // 个人信息，里面包含location
//        JSONObject selfInfo = new JSONObject();
//        // 包含city，province，street
//        JSONObject location = new JSONObject();
//        location.put("city","");
//        location.put("province","");
//        location.put("street","");
//        selfInfo.put("location",location);
//        perception.put("selfInfo",selfInfo);
        // 用户信息

        userInfo.put("apiKey",API_KEY);
        userInfo.put("userId",USER_ID);
        reqJson.put("perception",perception);
        reqJson.put("userInfo",userInfo);
        return reqJson;
    }

    public String tulinPost(Map<String, Object> params) {

        List<NameValuePair> pairs = new ArrayList<NameValuePair>();
        for (String key : params.keySet()) {
            pairs.add(new BasicNameValuePair(key, params.get(key).toString()));
        }
        StringBuilder result = new StringBuilder();
        HttpPost httpPost = new HttpPost(url);
        httpPost.addHeader("Content-type","application/json; charset=utf-8");
        httpPost.setHeader("Accept", "application/json");
        //UrlEncodedFormEntity par = new UrlEncodedFormEntity(pairs, "utf8");
        String toJson = new Gson().toJson(params);
        StringEntity par = new StringEntity(toJson,"utf-8");
        httpPost.setEntity(par);

        // HttpGet httpGet =new Http(url);
        HttpClientBuilder builder = null;
        try {
            //添加SSL认证
            SSLContextBuilder context_b = SSLContextBuilder.create();
            context_b.loadTrustMaterial(new TrustSelfSignedStrategy());
            SSLContext ssl_context = context_b.build();
            SSLConnectionSocketFactory sslSocketFactory = new SSLConnectionSocketFactory(ssl_context,new DefaultHostnameVerifier());
            builder = HttpClients.custom().setSSLSocketFactory(sslSocketFactory);
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (KeyStoreException e) {
            e.printStackTrace();
        } catch (KeyManagementException e) {
            e.printStackTrace();
        }
        try(
                //CloseableHttpClient httpClient = HttpClientBuilder.create().build();
                CloseableHttpClient httpClient = builder.build();
               CloseableHttpResponse httpResponse =httpClient.execute(httpPost);
        ){

            //把响应对象转成String
            // 解决中文乱码
            result.append(EntityUtils.toString(httpResponse.getEntity(),"utf8"));

        }catch (Exception e){
            e.printStackTrace();
            log.info("获取图灵机器人消息失败"+pairs);
        }
        return result.toString();
    }

    public String getMsg(String msg){
        String s = tulinPost(getReqMes(msg));
        JsonObject jsonObject =(JsonObject) new JsonParser().parse(s);
        JsonElement text = jsonObject.get("results").getAsJsonArray().get(0).getAsJsonObject().get("values").getAsJsonObject().get("text");
        String asString = text.getAsString();
        log.info("调用图灵机器人count:"+msg+"msg:"+asString);
        return asString ;
    }


}
